<template>
  <div class="app-container">

    <h2 align="center">发布课程</h2>

    <el-steps :active="active" process-status="wait" finish-status="success" align-center style="margin-bottom: 4px">
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="最终发布"></el-step>
    </el-steps>

    <!--    添加/编辑 章节对话框-->
    <el-dialog :title="chapterFormTitle" :visible.sync="dialogChapterFormVisible">
      <el-form :model="chapterForm" ref="chapterForm">
        <el-form-item label="章节标题" :label-width="formLabelWidth">
          <el-input v-model="chapterForm.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="章节排序" :label-width="formLabelWidth">
          <el-input-number v-model="chapterForm.sort"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogChapterFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdateChapterHandler" :disabled="saveLessonBtnDisable">确 定</el-button>
      </div>
    </el-dialog>

<!--    添加/编辑 小节(课时)对话框-->
<!--    TODO: vue-test-->
    <el-dialog :title="videoFormTitle" :visible.sync="dialogVideoFormVisible">
      <el-form :model="videoForm" ref="videoForm">
        <el-form-item label="课时标题" :label-width="formLabelWidth">
          <el-input v-model="videoForm.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="课时排序" :label-width="formLabelWidth">
          <el-input-number v-model="videoForm.sort" autocomplete="off" :min="0" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="是否免费" :label-width="formLabelWidth">
          <el-radio-group v-model="videoForm.free">
            <el-radio :label="true">免费</el-radio>
            <el-radio :label="false">默认</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="课时视频" :label-width="formLabelWidth">
          <el-link v-if="videoForm.videoSourceId" :href="videoForm.videoSourceId">
            {{ videoForm.videoOriginalName }} / {{ videoForm.videoSourceId }}
          </el-link>
          <el-upload
            :on-progress="handleVODProgress"
            :on-success="handleVodUploadSuccess"
            :on-error="handleVodUploadError"
            :on-preview="handleVodPreview"
            :before-remove="beforeVodRemove"
            :on-remove="handleVodRemove"
            :on-exceed="handleUploadExceed"
            :file-list="fileList"
            :url="BASE_API + '/vod/upload'"
            :action="BASE_API + '/vod/upload'"
            :limit="1"
            class="upload-video"
          >
            <el-button size="small" type="primary">{{ this.videoForm.videoSourceId ? "修改视频":"上传视频" }}</el-button>
            <el-tooltip placement="right-end">
              <div slot="content">
                最大支持100M单文件，
                <br />支持3GP、ASF、AVI、DAT、DV、FLV、F4V、
                <br />GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、
                <br />MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、
                <br />SWF、TS、VOB、WMV、WEBM 等视频格式上传
              </div>
              <i class="el-icon-question" />
            </el-tooltip>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onCancelEditLesson(videoForm.videoSourceId)">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdateLesson">确 定</el-button>
      </div>
    </el-dialog>

<!--    章节内容树-->
    <div class="chaptersContainer" style="width: 100%">
      <div class="addChapterHeader">
        <span>{{ courseInfo.title }}</span>
        <el-button type="primary" size="mini" class="addChapterButton" icon="el-icon-circle-plus" @click="addChapterHandler">添加章节</el-button>
      </div>

      <ul class="chapterList videoList">
        <li v-for="chapter in chapterList"
            :key="chapter.id"
            @mouseenter.stop.prevent="onMouseenter($event, chapter)"
            @mouseleave.stop.prevent="onMouseleave($event, chapter)"
            v-loading="loading">
          <p class="chapterContent">
            <span>{{ chapter.title }}</span>
            <span class="acts" v-show.sync="chapter.showActions">
            <el-button type="success" size="mini" icon="el-icon-plus" @click="onAddLessonHandler(chapter, courseId)">添加小节</el-button>
            <el-button type="normal"  size="mini" icon="el-icon-edit" @click="editChapterHandler(chapter.id)">编辑</el-button>
            <el-button type="danger"  size="mini" icon="el-icon-delete" @click="deleteChapterHandler(chapter.id)">删除</el-button>
          </span>
          </p>

          <!--        课程/小节 列表-->
          <ul class="chapterList videoList">
            <li v-for="video in chapter.children" :key="video.id"
                @mouseenter.stop.prevent="onMouseenter($event, video)"
                @mouseleave.stop.prevent="onMouseleave($event, video)">
              <p class="videoContent">
                <span>{{ video.title }}</span>
                <span class="acts" v-show="video.showActions">
                <el-button size="mini" icon="el-icon-edit" @click="onEditLessonHandler(chapter, video)">编辑</el-button>
                <el-button size="mini" icon="el-icon-delete" type="danger" @click="onDeleteLessonHandler(video.id)">删除</el-button>
              </span>
              </p>
            </li>
          </ul>
        </li>
      </ul>
    </div>

    <el-button-group class="stepActions">
      <el-button :hidden="true" :disabled="saveBtnDisabled" type="primary" style="margin-top: 12px;" @click="previous">上一步</el-button>
      <el-button :disabled="saveBtnDisabled" type="primary" style="margin-top: 12px;" @click="next">下一步</el-button>
    </el-button-group>

  </div>
</template>

<script>
import courseService from "@/api/edu/course";
import chapterService from '@/api/edu/chapter'
import videoService from '@/api/edu/video'
import vodService from "@/api/edu/vod";

import ChapterList from "@/components/edu/ChapterList";

export default {
  components: {ChapterList},
  data() {
    return {
      courseId: '',
      courseInfo: {},
      active: 2,
      saveBtnDisabled: false,
      saveLessonBtnDisable: false,
      filterText: '',
      formLabelWidth: '120px',
      loading: false,
      // fullscreenLoading: false,

      // 章节列表
      chapterList: [],
      defaultProps: {
        children: 'children',
        label: 'title',
      },

      // 添加章节表单
      dialogChapterFormVisible: false,
      chapterFormTitle: 'title',
      chapterForm: {
        title: '',
        sort: 0,
        id: '',
        courseId: '',
        showActions: false,
      },

      // 添加小节表单
      dialogVideoFormVisible: false,
      videoFormTitle: 'title',
      videoForm: {
        id: '',
        courseId: '',
        chapterId: '',
        title: '',
        sort: 0,
        free: true,
        videoSourceId: "",
        videoOriginalName: '',
        previousVideoSourceId: '',
      },
      fileList: [], //上传文件列表
      BASE_API: process.env.VUE_APP_BASE_API, // 接口API地址
    }
  },
  created() {
    this.checkCourseId()
    this.fetchData()
  },
  methods: {
    checkCourseId() {
      if (this.$route.params && this.$route.params.id) {
        this.courseId = this.$route.params.id
      }
    },
    fetchData() {
      this.loading = true
      // this.fullscreenLoading = true
      if (this.$route.params && this.$route.params.id) {
        const courseId = this.$route.params.id
        chapterService.getChapterVideo(courseId).then(res => {
          this.loading = false
          // this.fullscreenLoading = false
          this.chapterList = res.data.items;
          this.courseInfo = res.data.courseInfo
        })
      }
    },



    resetChapterForm() {
      // this.$refs["chapterForm"].resetFields()
      // this.chapterForm = {} // 不要这样清空表单，因为内部有一些系统创建的隐藏属性，清空后会导致表单响应异常
      this.chapterForm.title = ''
      this.chapterForm.sort = 0
    },
    resetVideoForm() {
      // this.$refs["chapterVideoForm"].resetFields()
      this.videoForm.title = ''
      this.videoForm.sort = 0
      this.videoForm.free = true
    },

    addChapterHandler() {
      // this.chapterFormTitle = '添加章节'
      this.chapterFormTitle = `${this.courseInfo.title} / 添加章节`
      this.chapterForm.sort = 0
      this.chapterForm.courseId = this.courseId
      this.dialogChapterFormVisible = true
    },
    saveOrUpdateChapterHandler() {
      if (this.chapterForm.id) {
        this.updateChapter()
      } else {
        this.insertChapter()
      }
    },
    editChapterHandler(chapterId) {
      chapterService.getChapter(chapterId).then(res => {
        this.chapterForm = res.data.data
        // this.chapterFormTitle = '编辑章节'
        this.chapterFormTitle = `${this.courseInfo.title} / 编辑章节`
        this.dialogChapterFormVisible = true
      })
    },
    deleteChapterHandler(chapterId) {
      this.$confirm('此操作将删除章节，是否继续？', '删除章节', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning",
      }).then(()=>{
        this.deleteChapter(chapterId)
      })
    },
    insertChapter() {
      chapterService.addChapter(this.chapterForm).then(res => {
        this.dialogChapterFormVisible = false
        this.fetchData()
        this.$message({
          type: "success",
          message: "添加章节成功"
        })
        this.resetChapterForm()
      })
    },
    updateChapter() {
      chapterService.updateChapter(this.chapterForm).then(res => {
        this.dialogChapterFormVisible = false
        this.fetchData()
        this.$message({
          type: "success",
          message: "修改章节成功"
        })
      })
    },
    deleteChapter(chapterId) {
      chapterService.deleteChapter(chapterId).then(res => {
        this.fetchData()
        this.$message({
          type: "success",
          message: "删除章节成功"
        })
      })
    },

    onAddLessonHandler(chapter, courseId) {
      this.videoFormTitle = '[添加课时]'
      const chapterId = chapter.id
      this.videoFormTitle = `${this.courseInfo.title} / ${chapter.title} / [添加课时]`
      this.videoForm.sort = 0
      this.videoForm.free = true
      this.videoForm.courseId = courseId
      this.videoForm.chapterId = chapterId
      this.videoForm.videoSourceId = ''
      this.videoForm.videoOriginalName = ''
      this.videoForm.previousVideoSourceId = ''
      this.dialogVideoFormVisible = true
    },
    onEditLessonHandler(chapter, video) {
      videoService.getVideo(video.id).then(res => {
        this.videoForm = res.data.data
        this.videoForm.previousVideoSourceId = res.data.data.videoSourceId
        console.log(this.videoForm)
        this.videoFormTitle = '编辑课时'
        this.videoFormTitle = `${this.courseInfo.title} / ${chapter.title} / [编辑课时]`
        this.dialogVideoFormVisible = true
      })
    },
    onDeleteLessonHandler(videoId) {
      this.$confirm('此操作将删除小节，是否继续？', '删除小节', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning",
      }).then(()=>{
        this.deleteLesson(videoId)
      })
    },
    onCancelEditLesson(videoSourceId) {
      console.log("用户取消操作，但是刚才上传的云端视频似乎还没删除")
      this.$message.warning('用户取消操作，云端视频似乎还没删除')
      // console.log('clear vod: ' + videoSourceId)
      this.dialogVideoFormVisible = false
      // if (videoSourceId) {
      //   vodService.deleteVideo(videoSourceId).then(res => {
      //     this.$message.success('用户取消操作，删除临时云端资源成功')
      //   })
      // }
    },
    saveOrUpdateLesson() {
      if (this.videoForm.id) {
        this.updateLesson()
      } else {
        this.addLesson()
      }
    },
    addLesson() {
      videoService.addVideo(this.videoForm).then(res => {
        this.dialogVideoFormVisible = false
        this.fetchData()
        this.$message({
          type: "success",
          message: "添加小节成功"
        })
        this.resetVideoForm()
      })
    },
    updateLesson() {
      // console.log(this.videoForm)
      videoService.updateVideo(this.videoForm).then(res => {
        this.dialogVideoFormVisible = false
        this.fetchData()
        this.$message({
          type: "success",
          message: "修改课时信息成功"
        })
      })
    },
    deleteLesson(videoId) {
        videoService.deleteVideo(videoId).then(res => {
          this.fetchData()
          this.$message({
            type: "success",
            message: "删除小节成功"
          })
        })
    },

    onMouseenter(event, item) {
      // event.stopPropagation()
      this.$set(item, 'showActions', true)
    },
    onMouseleave(event, item) {
      // event.stopPropagation()
      this.$set(item, 'showActions', false)
    },

    handleVodPreview(file, fileList) {
      console.log('handleVodPreview')
      console.log(file)
      console.log(fileList)
      this.$message.success("preview")
    },
    handleVODProgress(file, fileList) {
      this.$message.success("progress")
      this.saveLessonBtnDisable = true
    },
    //上传视频成功调用的方法
    handleVodUploadSuccess(response, file, fileList) {
      this.saveLessonBtnDisable = false
      console.log('handleVodUploadSuccess')
      console.log(file)
      console.log(fileList)
      // if (response.data.videoSourceId) {
      //   this.$message.success("视频确认上传成功")
      // } else {
      //   this.$message.error("视频上传失败")
      // }
      //上传视频id赋值
      this.videoForm.videoSourceId = response.data.videoSourceId;
      //上传视频名称赋值
      this.videoForm.videoOriginalName = file.name;
      console.log(this.videoForm)
    },
    handleVodUploadError() {
      this.$message.error("上传视频失败")
    },
    handleUploadExceed() {
      this.$message.warning("想要重新上传视频，请先删除已上传的视频");
    },
    //点击×调用这个方法
    beforeVodRemove(file, fileList) {
      console.log(`beforeRemove videoSourceId: ${file.response.data.videoSourceId}`)
      console.log(file)
      console.log(fileList)
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleVodRemove(file) {
      //调用接口的删除视频的方法
      console.log(`remove videoSourceId: ${file.response.data.videoSourceId}`)
      vodService.deleteVideo(this.videoForm.videoSourceId).then(response => {
        //提示信息
        this.$message.success("删除视频成功!")
        //把文件列表清空
        this.fileList = [];
        //把video视频id和视频名称值清空
        //上传视频id赋值
        this.videoForm.videoSourceId = "";
        //上传视频名称赋值
        this.videoForm.videoOriginalName = "";
      });
    },


    filterNode(value, data) {
      if (!value) return true
      return data.label.toLowerCase().indexOf(value.toLowerCase()) !== -1
    },

    previous() {
      // if (this.active++ > 2) this.active = 1;
      this.$router.push(`/course/info/${this.courseId}`)
    },
    next() {
      // if (this.active++ > 2) this.active = 1;
      this.$router.push(`/course/publish/${this.courseId}`)
    },
  }
}
</script>

<style scoped>
.addChapterHeader {
  margin: 10px 0;
  padding-left: 50px;
  font-size: 20px;
}
.addChapterButton {
  float: right;
  position: relative;
}
.stepActions {
  float: right;
  position: relative;
  margin-bottom: 30px;
}

.chapterList {
  position: relative;
  list-style: none;
  margin: 0;
  padding: 0;
}
.chapterList li {
  position: relative;
}
.chapterList .chapterContent {
  float: left;
  font-size: 20px;
  margin: 10px 0;
  padding: 6px;
  height: 50px;
  line-height: 50px;
  background-color: #d4e5e1;
  width: 100%;
  border: 1px solid #ddd;
}
.chapterList .acts {
  float: right;
  font-size: 20px;
}

.videoList {
  padding-left: 50px;
}
.videoList .videoContent {
  float: left;
  font-size: 14px;
  margin: 5px 0;
  padding: 3px;
  background-color: #caaed2;
  height: 40px;
  line-height: 30px;
  width: 100%;
  border: 1px dotted #ddd;
}
.videoList .acts {
  float: right;
  font-size: 14px;
}
</style>
